import { BrowserWindow, shell, session } from 'electron'
import icon from '../../resources/icon.png?asset'
import { join } from 'path'

export default class BrowserInstance {
  url: string
  window: BrowserWindow

  constructor(url: string, onClose: () => void) {
    this.url = url

    this.window = new BrowserWindow({
      width: 1000,
      height: 800,
      show: false,
      autoHideMenuBar: true,
      ...(process.platform === 'linux' ? { icon } : {}),
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false,
        webviewTag: true
      }
    })

    this.window.on('closed', () => {
      onClose()
    })

    this.window.on('ready-to-show', () => {
      this.window.show()
    })

    this.window.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'allow' }
    })

    this.window.loadURL(url)
  }

  async getLocalstorage() {
    return await this.window.webContents.executeJavaScript('JSON.stringify(localStorage)')
  }

  async getCookies() {
    const data = await session.defaultSession.cookies.get({ url: this.url })
    return data.map((cookie) => ({
      name: cookie.name,
      value: cookie.value,
      domain: cookie.domain,
      path: cookie.path
    }))
  }
}
